import 'package:flutter/material.dart';
import 'package:shenling_project/utils/eventBus.dart';
import 'package:shenling_project/utils/request.dart';

import '../utils/toast.dart';
import '../utils/tokenManager.dart';

class Minepage extends StatefulWidget {
  const Minepage({super.key});

  @override
  State<Minepage> createState() => _MinepageState();
}

class _MinepageState extends State<Minepage> {
  final List taskListData = [
    {'num': 18, 'title': '任务总量'},
    {'num': 16, 'title': '完成任务量'},
    {'num': 3987, 'title': '运输里程(km)'},
  ];

  bool _isLoading = false;

  final List menuData = [
    //文字和右箭头图标
    {'id': 0, 'title': '车辆信息', 'icon': 'assets/images/right.png'},
    {'id': 1, 'title': '任务数据', 'icon': 'assets/images/right.png'},
    {'id': 2, 'title': '系统设置', 'icon': 'assets/images/right.png'},
  ];
  //用户信息
  Map _userInfo = {'avatar': '', 'number': 0, 'name': '', 'phone': ''};

//本月任务builder
  Widget tastBuilder(item) {
    return Column(
      children: [
        Text(
          item['num'].toString(),
          style: const TextStyle(
              fontSize: 18,
              color: Color.fromRGBO(42, 41, 41, 1),
              fontWeight: FontWeight.w600),
        ),
        const SizedBox(
          height: 15,
        ),
        Text(
          item['title'],
          style: const TextStyle(
              fontSize: 12,
              color: Color.fromRGBO(42, 41, 41, 1),
              fontWeight: FontWeight.w400),
        )
      ],
    );
  }

//菜单builder
  Widget menuBuilder(item) {
    return SizedBox(
        height: 40,
        child: GestureDetector(
          onTap: () {
            if (item['id'] == 2) {
              //跳转登录页
              final token = TokenManager().getToken() ?? '';
              if (token.isNotEmpty) {
                Navigator.of(context).pushNamed('/setting');
              } else {
                Navigator.of(context).pushNamed('/login');
              }
            }
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item['title']),
              Image.asset(
                item['icon'],
                width: 24,
                height: 24,
              )
            ],
          ),
        ));
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    event.on<LoginGetData>().listen((event) {
      _getUserInfo();
    });
  }

//获取用户信息
  _getUserInfo() async {
    try {
      setState(() {
        _isLoading = true;
      });
      final res = await http.request('get', '/driver/users', null, null);
      // print(res);
      if (res['code'] != 200) return ToastUtil.showError('获取用户信息失败!');

      Future.delayed(const Duration(seconds: 1), () {
        setState(() {
          _userInfo = res['data'];
          _isLoading = false;
        });
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 设置主体内容
      body: _isLoading
          ? const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(
                    height: 10,
                  ),
                  Text('加载中')
                ],
              ),
            )
          : Container(
              color: Colors.grey,
              child: Column(
                children: [
                  //上方
                  Container(
                    width: MediaQuery.of(context).size.width,
                    height: 300,
                    decoration: const BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(50),
                            bottomRight: Radius.circular(50))),
                    child: Column(
                      children: [
                        //头像
                        Container(
                          margin: const EdgeInsets.only(top: 50),
                          child: GestureDetector(
                            onTap: () {
                              String token = TokenManager().getToken() ?? '';
                              if (token.isNotEmpty) {
                              } else {
                                Navigator.pushNamed(context, '/loign');
                              }
                            },
                            child: _userInfo['avatar'] == ''
                                ? Image.asset(
                                    'assets/images/avatar.png',
                                    width: 66,
                                    height: 66,
                                  )
                                : Image.network(
                                    _userInfo['avatar'],
                                    width: 66,
                                    height: 66,
                                  ),
                          ),
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        //姓名
                        _userInfo['name'] == ''
                            ? const Text(
                                '您未登录',
                                style: TextStyle(
                                    fontSize: 20,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600),
                              )
                            : Text(
                                _userInfo['name'],
                                style: const TextStyle(
                                    fontSize: 20,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600),
                              ),
                        const SizedBox(
                          height: 10,
                        ),
                        //司机编号
                        _userInfo['number'] == ''
                            ? const Text(
                                '司机编号: 您未登录',
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w400),
                              )
                            : Text(
                                '司机编号: ${_userInfo['number']}',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w400),
                              ),
                        const SizedBox(
                          height: 10,
                        ),
                        //手机号
                        _userInfo['phone'] == ''
                            ? const Text(
                                '手机号: 您未登录',
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w400),
                              )
                            : Text(
                                '手机号: ${_userInfo['phone']}',
                                style: const TextStyle(
                                    fontSize: 14,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w400),
                              )
                      ],
                    ),
                  ),

                  //白色任务卡片
                  Transform.translate(
                      offset: const Offset(0, -40),
                      child: Container(
                          margin: const EdgeInsets.only(left: 16, right: 16),
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white,
                          ),
                          height: 140,
                          child: Column(
                            children: [
                              const SizedBox(
                                height: 10,
                              ),
                              // 第一行本月任务
                              const Text(
                                '- 本月任务 -',
                                style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.w400,
                                    color: Color.fromRGBO(129, 129, 129, 1)),
                              ),
                              const SizedBox(
                                height: 20,
                              ),
                              //任务卡片
                              Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: taskListData.map((item) {
                                    return tastBuilder(item);
                                  }).toList())
                            ],
                          ))),

                  //菜单栏
                  Container(
                    width: MediaQuery.of(context).size.width,
                    height: 180,
                    margin: const EdgeInsets.only(left: 16, right: 16),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                    ),
                    child: ListView.separated(
                        padding: EdgeInsets.zero,
                        physics: const ClampingScrollPhysics(),
                        shrinkWrap: true,
                        itemBuilder: (ctx, index) {
                          return Container(
                            padding: const EdgeInsets.all(10),
                            child: menuBuilder(menuData[index]),
                          );
                        },
                        separatorBuilder: (ctx, index) {
                          return const Divider(
                            height: 1,
                            indent: 12,
                            endIndent: 12,
                          );
                        },
                        itemCount: menuData.length),
                  )
                ],
              ),
            ),
    );
  }
}
